// base64_client.cpp
#include "base64_client.h"

// 初始化 Base64 编码表
const std::string Base64Client::base64_chars = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";

unsigned char *convertInt16VectorToUnsignedCharArray(const std::vector<int16_t> &input)
{
    size_t outputSize = input.size() * sizeof(int16_t);
    unsigned char *data = new unsigned char[outputSize];
    const char *inputData = reinterpret_cast<const char *>(input.data());
    for (size_t i = 0; i < outputSize; ++i)
    {
        data[i] = static_cast<unsigned char>(inputData[i]);
    }
    return data;
}
// Base64 编码函数实现
std::string Base64Client::Base64Encode(const std::vector<int16_t>& input) {
    unsigned char* data = convertInt16VectorToUnsignedCharArray(input);
    size_t dataLen = input.size() * sizeof(int16_t);
    std::string base64Result = Base64EncodeStr(data,dataLen);
    // 释放动态分配的内存
    delete[] data;
    return base64Result;
}

// Base64 编码函数实现
std::string Base64Client::Base64EncodeStr(const unsigned char *data, size_t len){
    const char *base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    std::string encoded;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    size_t i = 0;
    while (i < len)
    {
        size_t chunk_size = std::min((size_t)3, len - i);

        for (size_t j = 0; j < 3; j++)
        {
            char_array_3[j] = (j < chunk_size) ? data[i + j] : 0;
        }

        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        char_array_4[3] = char_array_3[2] & 0x3f;

        for (size_t j = 0; j < 4; j++)
        {
            if (j <= chunk_size)
            {
                encoded.push_back(base64_chars[char_array_4[j]]);
            }
            else
            {
                encoded.push_back('=');
            }
        }

        i += chunk_size;
    }
    return encoded;
}



// Base64 解码函数实现
std::vector<int16_t> Base64Client::Base64Decode(const std::string& input) {
    std::vector<int16_t> output;
    size_t input_length = input.length();
    if (input_length % 4 != 0) {
        return output;
    }

    size_t output_size = input_length / 4 * 3;
    if (input[input_length - 1] == '=') output_size--;
    if (input[input_length - 2] == '=') output_size--;

    std::vector<uint8_t> decoded_bytes(output_size);
    size_t i, j;
    for (i = 0, j = 0; i < input_length; ) {
        uint32_t sextet_a = base64_chars.find(input[i++]);
        uint32_t sextet_b = base64_chars.find(input[i++]);
        uint32_t sextet_c = base64_chars.find(input[i++]);
        uint32_t sextet_d = base64_chars.find(input[i++]);

        uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);

        if (j < output_size) decoded_bytes[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < output_size) decoded_bytes[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < output_size) decoded_bytes[j++] = (triple >> 0 * 8) & 0xFF;
    }

    output.resize(decoded_bytes.size() / sizeof(int16_t));
    std::memcpy(output.data(), decoded_bytes.data(), decoded_bytes.size());

    return output;
}

// 简单的 UUID 生成函数（模拟）
std::string Base64Client::GenerateUuid() {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    std::string uuid;
    for (int i = 0; i < 36; ++i) {
        if (i == 8 || i == 13 || i == 18 || i == 23) {
            uuid += '-';
        } else {
            uuid += alphanum[rand() % (sizeof(alphanum) - 1)];
        }
    }
    return uuid;
}

std::string Base64Client::ConstructUpdateConfigReq(){
    // 构建要发送的消息
    std::string uuid = GenerateUuid();
    std::string req_json = std::string("{\"data\": {\"chat_config\": {\"auto_save_history\": true,\"user_id\": \"mss\"},\"input_audio\": {\"format\":\"pcm\",\"bit_depth\": 16,\"channel\": 1,\"sample_rate\": 16000},\"output_audio\": {\"speech_rate\": 0,\"voice_id\":\"7446675275930271784\"}},\"event_type\": \"chat.update\",\"id\": \"2c86d292-3a22-4d61\"}");
    return req_json;
}

std::string Base64Client::ConstructAudioMsgReq(const std::vector<int16_t>& input_audio){
    
    std::string audioData = Base64Encode(input_audio);

    // 构建要发送的消息
    std::string uuid = GenerateUuid();

    std::string req_json = std::string("{\"id\":\"" + uuid + "\",");
    req_json += "\"event_type\":\"input_audio_buffer.append\",";
    req_json += "\"data\":{\"delta\":\"" + audioData + "\"}}";

    return req_json;
}

std::string Base64Client::ConstructAudioFinishMsgReq(){
    // 构建要发送的消息
    std::string uuid = GenerateUuid();
    std::string req_json = std::string("{\"id\":\"" + uuid + "\",");
    req_json += "\"event_type\":\"input_audio_buffer.complete\"}";
    return req_json;
}

